import React, { Component } from 'react';
import "../assets/css/parKingManage.css"

import { Modal } from 'antd';
import { Form, Input, Tooltip, Icon, Cascader, Select, Row, Col, Checkbox, Button, AutoComplete,Pagination  } from 'antd';

import { enteringParkingInfo,threeLevelLinkage,getParkInfoList,delParkInfo,getParkInfo,threeLevelLinkager,modifyParkInfo} from "../assets/js/api.js";
// 单选框
import { Radio,message } from 'antd'
import axios from 'axios'
const RadioGroup = Radio.Group;

// 这边是顶部城市的选择;
const Option = Select.Option;

// 省份选择框的变化



// 这边是录入停车场信息的相关
const FormItem = Form.Item;
const AutoCompleteOption = AutoComplete.Option;



class NormalLoginForm  extends Component {

  constructor(props){
    super(props);
    this.state = {
      showDelect:false,
      isLoading:false,
      ModalText: 'Content of the modal',
      visible: false,
      confirmLoading: false,
      confirmDirty: false,
      autoCompleteResult: [],
      modelDefaultValue:{
        kefuname:"你啥",
        chechangname:"5ming",
        residence:['zhejiang', 'hangzhou', 'xihu'],
        detailsAdress:"肖家吞",
        value: 1,
        lal:""
      },
      residences : [],
      ParkInfoList:[],  // 停车场信息接口;
      total:1 ,  // 这=这边是总页数
      isDeleteid:"",  // 要删除的id
      isDeleteIndex:"",  // 要删除index
      shengList:[], // 这边是单次省份的列表
      shiList:[], //这边是市的东西。
      shiValue:"", //城市的值
      provinceId:"全国",
      cityId:"不限",
      parkType:"全部",
      type:1,  //  1 代表着新增，-1 代表着编辑；
      parkId :"",   //  这边是用于编辑用的；
      pageNo:1   //这个代表着当前页数；
    }
 }


 handleChange1=(value)=> {

  let data = [2,value]
  this.threeLevelLinkager(data,2)
  this.setState({
    shiValue:"不限",
    provinceId:value,
    cityId:"不限",
    shiList:[]


  },()=>{
    this. getParkInfoList(1)
  });
}


 handleChange2=(value)=> {
  this.setState({
    shiValue:value,
    cityId:value
  },()=>{
    this. getParkInfoList(1)
  });
}

// 这边是第三个选择；
 handleChange3=(value)=> {

  this.setState({
    parkType:value
  },()=>{
    this. getParkInfoList(1)
  });

}

// 添加停车场是否直营；
 onChange = (e) => {
  console.log('radio checked', e.target.value);
  this.setState({
    modelDefaultValue:{
      kefuname:this.state.modelDefaultValue.kefuname,
      chechangname:this.state.modelDefaultValue.chechangname,
      residence:this.state.modelDefaultValue.residence,
      detailsAdress:this.state.modelDefaultValue.detailsAdress,
      value: e.target.value,
      lal:this.state.modelDefaultValue.lal
    }
  });
}

// 点击显示录入停车场；
async showModal (type,parkInfoId) {

  //清除form 里面的数据；
   this.props.form.resetFields()

    // 如果一代表着新增
     if(type==1){

        this.setState({
          type:1,
          modelDefaultValue:{
            kefuname:"",
            chechangname:"",
            residence:[],
            detailsAdress:"",
            value: 1,
           },
        });
     }

    //  如果是-1代表着编辑;
    if(type==-1){
      try {
        var data = [parkInfoId]
        const res = await getParkInfo(data);
        console.log(res)
        if (res.data.code == 200 && res.data.ifsuccess) {

          console.log("编辑")
          console.log(res)

             // 下面是一个设置
              this.setState({
                type:-1,
                parkId:res.data.result.parkId,
                modelDefaultValue:{
                  kefuname:res.data.result.businessName,
                  chechangname:res.data.result.parkName,
                  residence:[res.data.result.provinceId,res.data.result.cityId,res.data.result.areaId],
                  detailsAdress:res.data.result.parkAddress,
                  value: res.data.result.whetherDirectly,
                  lal: res.data.result.lal
                },
              });

          } else {
            message.error("获取详情失败");
          }
        } catch (err) {
            message.error("获取详情失败");
        }



   }





    this.setState({
      visible: true,
    });

  }


  //显示删除的弹框
  showCancerModal = (index,parkInfoId) => {
     this.setState({
      showDelect: true,
      isDeleteid:parkInfoId,
      isDeleteIndex:index
     });
  }


  // 这边是确认删除的弹框
   isDelete= async() =>{
    this.setState({
      isLoading: true
    });

    // alert(55)
    // alert(this.state.isDeleteIndex)
    // alert(this.state.isDeleteid)

    try {
      var data = [this.state.isDeleteid]
      const res = await delParkInfo(data);
      console.log(res)
      if (res.data.code == 201 && res.data.ifsuccess) {
            message.success("删除成功");

            var ParkInfoList = this.state.ParkInfoList;
               ParkInfoList.splice(this.state.isDeleteIndex, 1)
              this.setState({
                showDelect: false,
                isLoading: false,
                ParkInfoList:ParkInfoList
              });

      } else {
         message.error("删除失败");
      }
    } catch (err) {
         message.error("删除失败");
    }


  }

  // 这边是删除弹框的取消
  notDelete = () => {
    this.setState({
      showDelect: false,
    });
  }




  handleCancel = () => {
    console.log('Clicked cancel button');
    this.setState({
      visible: false,
    });
  }



   threeLevelLinkager = async(data,type) => {

      try {
        const res = await threeLevelLinkager(data);
        if (res.data.code == 200 && res.data.ifsuccess) {
          console.log("获取省份")
          console.log(res)
        // 这边是填充省份
          if(type===1){
            this.setState({
              shengList: res.data.result,
              shiValue:"不限"
            });


          }
          // 填充市选择框；
          if(type===2){
            this.setState({
              shiList:res.data.result
            });
          }

        } else {
          throw new Error("获取数据失败");
        }
      } catch (err) {
        console.log("获取数据失败", err);
    }
  }



  // 组件刚要加载;
  async  componentWillMount(){

    //获取省份
    let data = [1,20]
    this.threeLevelLinkager(data,1)




    // 获取三级联动
       try {
          const res = await threeLevelLinkage([]);
          if (res.data.code == 200 && res.data.ifsuccess) {
            console.log(res)

            this.setState({
              residences: res.data.result
            });


          } else {
            throw new Error("获取数据失败");
          }
        } catch (err) {
          console.log("获取数据失败", err);
      }


      this.getParkInfoList(1)

  }

  //  得到停车场列表；
   async getParkInfoList(num){




    let provinceId = this.state.provinceId;

    if(provinceId == "全国"){

      provinceId =""
    }


    let cityId = this.state.cityId;
    if(cityId=="不限"){
      cityId = ""
    }else{
      cityId = this.state.cityId;
    }

    let parkType = this.state.parkType;

    if(parkType=="全部"){
      parkType= ""
    }else{
       parkType = this.state.parkType;

    }


      try {

        var data = {
          provinceId:provinceId,
          cityId:cityId,
          parkType:parkType,
          pageSize:12,
          pageNo:num
        }
        const res = await getParkInfoList(data);
        console.log(res)
        if (res.data.code == 200 && res.data.ifsuccess) {

          if(!res.data.result.list.length){
            message.success("暂无数据");

          }
          this.setState({
            ParkInfoList:res.data.result.list,
            total : res.data.result.total,
            pageNo : num
          });
        } else {
          throw new Error("获取数据失败");
        }
       } catch (err) {
        console.log("获取数据失败", err);
      }
  }

  // 删除停车场
  // async delParkInfo(parkInfoId){

  //     try {
  //       var data = [parkInfoId]
  //       const res = await delParkInfo(data);
  //       console.log(res)
  //       if (res.data.code == 200 && res.data.ifsuccess) {
  //             message.success("删除成功");
  //       } else {
  //          message.error("删除失败");
  //       }
  //     } catch (err) {
  //          message.error("删除失败");
  //     }

  // }




  handleSubmit = (e) => {

    e.preventDefault();
    this.props.form.validateFieldsAndScroll(async(err, values) => {
      if (!err) {

        this.setState({
          ModalText: 'The modal will be closed after two seconds',
           confirmLoading: true,
           });
          setTimeout(() => {
            this.setState({
             visible: false,
             confirmLoading: false,
           });
          }, 10);




  //  新增停车场
    if(this.state.type==1){

          try {
            var data = {
              businessName: values.kefuname,
              parkName: values.chechangname,
              parkAddress: values.detailsAdress,
              provinceId: values.residence[0],
              cityId: values.residence[1],
              areaId: values.residence[2],
              whetherDirectly: this.state.modelDefaultValue.value,
              lal:values.lal
            }
            const res = await enteringParkingInfo(data);
            console.log(res)
            if (res.data.code == 201 && res.data.ifsuccess) {

                message.success("操作成功");
                // 成功后弹框消失
              this.setState({
                provinceId: "全国",
                cityId:"不限",
                parkType:"全部",
                  modelDefaultValue:{
                    kefuname:"",
                    chechangname:"",
                    residence:[],
                    detailsAdress:"",
                    value: 1,
                  }
                },()=>{
                  this.getParkInfoList(1)
                });



            } else {
              message.error(res.data.msg);
            }
          } catch (err) {
            message.error("服务器正忙");
        }


    }else{
    // 编辑停车场

          try {
            var data = {
              parkId:this.state.parkId,
              businessName: values.kefuname,
              parkName: values.chechangname,
              parkAddress: values.detailsAdress,
              provinceId: values.residence[0],
              cityId: values.residence[1],
              areaId: values.residence[2],
              whetherDirectly: this.state.modelDefaultValue.value,
              lal:values.lal
            }
            const res = await modifyParkInfo(data);
            console.log(res)
            if (res.data.code == 201 && res.data.ifsuccess) {

                message.success("操作成功");
                // 成功后弹框消失
              this.setState({

                  modelDefaultValue:{
                    kefuname:"",
                    chechangname:"",
                    residence:[],
                    detailsAdress:"",
                    value: 1,
                  }
                },()=>{
                  this.getParkInfoList(this.state.pageNo)
                });

            } else {
              message.error(res.data.msg);
            }
          } catch (err) {
            message.error("服务器正忙");
        }



    }











    // enteringParkingInfo(data).then((res)=>{
    //   console.log(res)
    // },err=>{
    //   console.log(err)
    // })

      }
    });
  }


  render() {


    const { getFieldDecorator } = this.props.form;
    const { autoCompleteResult } = this.state;

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
    };
    const tailFormItemLayout = {
      wrapperCol: {
        xs: {
          span: 24,
          offset: 0,
        },
        sm: {
          span: 16,
          offset: 8,
        },
      },
    };

    const websiteOptions = autoCompleteResult.map(website => (
      <AutoCompleteOption key={website}>{website}</AutoCompleteOption>
    ));

    return (
  <div className="parking">


     {/*这边是顶部的停车场管理 */}
    <section className="tittle_box">

       <div>
            <div className="tittle">停车场管理</div>

            <section  className="flex_section">

                <div className="select_box">

                  <div>
                 城市选择

                  <Select className="citySelect" value ={this.state.provinceId}  style={{ width: 120 }} onChange={this.handleChange1}>
                      <Option value="全国">全国</Option>

                      {
                      this.state.shengList.map((item,index)=>{
                       return  <Option key = {item} value={item.value}>{item.label}</Option>
                       })

                      }
                    </Select>
                  </div>

                  <div>
                    不限
                    <Select className="noLimit" value ={this.state.cityId} allowclear  style={{ width: 120 }} onChange={this.handleChange2}>

                      <Option value="不限">不限</Option>

                      {
                      this.state.shiList.map((item,index)=>{
                       return  <Option key = {item} value={item.value}>{item.label}</Option>
                       })

                      }
                    </Select>
                  </div>


                <div>
                  类别
                  <Select className="noLimit" value={this.state.parkType} style={{ width: 120 }} onChange={this.handleChange3}>
                    <Option value="全部">全部</Option>
                    <Option value="1">自营</Option>
                    <Option value="2">非自营</Option>

                  </Select>
                  </div>
             </div>

              <div>

                <div className="write" onClick={(e)=>{this.showModal(1,"")}}>
                   +录入停车场
                </div>
             </div>

         </section>

       </div>

    </section>

    {/* 这边是下面停车场的部分 */}

    <section className="next_content">
        <div className="minHeigth">
            <div className="list_box">


           {/* 下面是一个循环体 */}
            {this.state.ParkInfoList.map((item, index) => {
            return (
               <div key={index}  className="list">
                  <div className="list_top">
                      <img className="logo-icon"  src={require('../assets/img/logo-icon.png')} alt=""/>
                        <div>

                          <div  className="text_ying" >
                           <div  className="ying_top">{(item.parkName.length>8)?item.parkName.slice(0,7)+"...":item.parkName}</div>
                          {
                            (item.whetherDirectly==1)? <div  className="ying">营</div> : null
                          }

                          </div>
                          <div>
                            <span className="gold-icon-span">
                              <img className=""  src={require('../assets/img/gold-icon.png')} alt=""/>{item.price?item.price:"未上传"}
                            </span>
                            <span className="ParkingSpaces-span">
                              <img  className="ParkingSpaces" src={require('../assets/img/ParkingSpaces.png')} alt=""/> <span className="padding_padding">{item.vacancy?item.vacancy+"个":"未上传"}</span>
                            </span>

                          </div>
                      </div>
                    </div>
                    <div className="list_bottom">
                      <div className="parkAddress">
                          {item.parkAddress}
                      </div>
                      <div>
                        <img className="delete_delete"  onClick={(e)=>{this.showCancerModal(index,item.parkId)}}  src={require('../assets/img/delete.png')} alt=""/>
                        <img className="editor"  onClick={(e)=>{this.showModal(-1,item.parkId)}}  src={require('../assets/img/editor.png')} alt=""/>
                      </div>
                    </div>
               </div>
             )
            })}

              {/*上面是一个循环体*/}



          </div>


        </div>


          <Pagination   className="fenYe"  pageSize={12}   showQuickJumper defaultCurrent={1} total={this.state.total} onChange={(e)=>{this.getParkInfoList(e)}} />


    </section>

       {/*下面是弹框的部分*/}

      <Modal
          title="录入停车场"
          visible={this.state.visible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
          footer={null
            // <div className="addServiceBtn">
            // <Button key="back" onClick={this.handleCancel}>取消</Button>
            // <Button key="submit" onClick={this.handleOk} type="primary"
            //   loading={this.state.confirmLoading}>
            //    确定
            // </Button>
            // </div>
          }
          cancelText = '取消'>
           {/* 录入停车场的信息的容器 */}
           <div className="Form_div_box">

                      <Form  className="Form_Form" onSubmit={this.handleSubmit}>


                        <FormItem
                          {...formItemLayout}
                          label={(
                            <span>
                               客服名称&nbsp;
                            </span>
                          )}
                        >
                          {getFieldDecorator('kefuname', {
                             initialValue:this.state.modelDefaultValue.kefuname,
                            rules: [{ required: true, message: '请输入客服名称' }],
                          })(
                            <Input />
                          )}
                        </FormItem>


                         <FormItem
                          {...formItemLayout}
                          label={(
                            <span>
                               车场名称&nbsp;
                            </span>
                          )}
                        >
                          {getFieldDecorator('chechangname', {
                            initialValue:this.state.modelDefaultValue.chechangname,
                            rules: [{ required: true, message: '请输入车场名称' }],
                          })(
                            <Input />
                          )}
                        </FormItem>


                        <FormItem
                          {...formItemLayout}
                          label="设置地址"
                        >
                          {getFieldDecorator('residence', {
                            initialValue: this.state.modelDefaultValue.residence,
                            rules: [{ type: 'array', required: true, message: '请设置地址' }],
                          })(
                            <Cascader options={this.state.residences} />
                          )}
                        </FormItem>


                        <FormItem
                          {...formItemLayout}
                          label={(
                            <span>
                               具体地址&nbsp;
                            </span>
                          )}
                        >
                          {getFieldDecorator('detailsAdress', {
                            initialValue:this.state.modelDefaultValue.detailsAdress,
                            rules: [{ required: true, message: '请输入具体地址' }],
                          })(
                            <Input />
                          )}
                        </FormItem>

                           <FormItem
                          {...formItemLayout}
                          label={(
                            <span>
                               具体经纬度&nbsp;
                            </span>
                          )}
                        >

                          {getFieldDecorator('lal', {
                            initialValue:this.state.modelDefaultValue.lal,
                            rules: [{ required: false, message: '请输入地址的经纬度（非必填）' }],
                          })(
                            <Input />
                          )}
                        </FormItem>
                         <a  className="jingweidu" target="view_window" href="https://lbs.amap.com/console/show/picker">查询经纬度</a>
 

                          <FormItem
                          {...formItemLayout}
                          label={(
                            <span>
                               是否直营&nbsp;
                            </span>
                          )}
                        >
                           {/* {getFieldDecorator('chechangname', {
                            rules: [{ required: true, message: '请输入具体地址', whitespace: true }],
                          })(
                             */}
                            <RadioGroup onChange={this.onChange} value={this.state.modelDefaultValue.value}>
                            <Radio value={1}>直营停车场</Radio>
                             <Radio value={2}>合作停车场</Radio>
                             </RadioGroup>
                                   {/* )}  */}
                        </FormItem>



                          <div className="addServiceBtnAdd">
                            <Button key="back" onClick={this.handleCancel}>取消</Button>
                            <Button  htmlType="submit" key="submit" onClick={this.handleOk} type="primary"
                              loading={this.state.confirmLoading}>
                              确定
                            </Button>
                            </div>
                          {/* <Button type="primary" htmlType="submit">注册</Button> */}
                      </Form>
          </div>
        </Modal>

           {/*下面是删除的弹框*/}

             <Modal title="删除停车场"
                           visible={this.state.showDelect}
                           confirmLoading={this.state.isLoading}
                           onOk={this.isDelete}
                           onCancel={this.notDelete}
                           footer={
                               <div className="deleteBtn">
                                   <Button className="cancerButton" key="back" onClick={this.notDelete}>取消</Button>
                                   <Button className="cancerButton" key="submit" onClick={this.isDelete} type="primary"
                                           loading={this.state.isLoading}>
                                       确定
                                   </Button>
                               </div>
                           }
                    >
                        <p className="deleteMsgTip">确认要删除停车场吗</p>
              </Modal>


      </div>
    );
  }
}







let parKingManage = Form.create()(NormalLoginForm );


export default parKingManage;




